// 大华播放器
import { ref, onUnmounted } from 'vue'
const useVideoPlayer = () => {
  const flvPlayers = ref([])
  const hlsPlayers = ref([])

  const playHLS = (url, id) => {
    const video = document.getElementById(id)
    if (Hls.isSupported()) {
      let hlsPlayer = new Hls()
      hlsPlayer.loadSource(url)
      hlsPlayer.attachMedia(video)
      hlsPlayer.on(Hls.Events.MANIFEST_PARSED, function () {
        video.play()
      })
      hlsPlayers.value.push(hlsPlayer)
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = url || ''
      video.addEventListener('loadedmetadata', () => {
        video.play()
      })
    }
  }

  const playFlv = (url, id) => {
    const video = document.getElementById(id)
    let flvPlayer = dhflvjs.createPlayer({
      type: 'flv',
      url: url,
    })
    flvPlayer.attachMediaElement(video)
    flvPlayer.load()
    flvPlayer.play()
    flvPlayers.value.push(flvPlayer)
  }
  const playVideo = (video) => {
    if (video.mode === 'hls') {
      playHLS(video.url, video.id)
    } else {
      playFlv(video.url, video.id)
    }
  }

  const destroyed = () => {
    flvPlayers.value.forEach((player) => {
      if (player) {
        player.unload()
        player.detachMediaElement()
        player.destroy()
      }
    })
    flvPlayers.value = []
    hlsPlayers.value.forEach((player) => {
      if (player) {
        player.destroy()
      }
    })
    hlsPlayers.value = []
  }
  onUnmounted(() => {
    destroyed()
  })

  return {
    playHLS,
    playFlv,
    playVideo,
    destroyed,
  }
}

export default useVideoPlayer
